import store from '@/store';
import { Toast } from 'antd-mobile';
import axios from 'axios';
import history from './history';
import { getAuth, getToken, setAuth } from './storage';

export const baseURL = 'http://geek.itheima.net';

const http = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

http.interceptors.request.use(
  function (config) {
    if (getToken()) {
      (config.headers as any).Authorization = `Bearer ${getToken()}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  function (response) {
    return response.data;
  },
  async function (error) {
    if (!error.response) {
      Toast.show({ content: '网络有问题，请检查网络' });
      return Promise.reject(error);
    }
    if (error.response.status !== 401) {
      Toast.show({ content: error.response.data.message });
      return Promise.reject(error);
    }

    const { refresh_token } = getAuth();

    if (!refresh_token) {
      history.push('/login');
      Toast.show({ content: '登录超时，重新登录' });
      return Promise.reject(error);
    }

    try {
      const res = await axios({
        url: baseURL + '/v1_0/authorizations',
        method: 'put',
        headers: {
          Authorization: 'Bearer ' + refresh_token,
        },
      });
      const auth = { token: res.data.data.token, refresh_token };
      setAuth(auth);
      store.dispatch({ type: 'user/saveAuth', payload: auth });
      return http(error.config);
    } catch (error) {
      console.dir(error);
      history.push('/login');
      Toast.show({ content: '登录超时，重新登录' });
      return Promise.reject(error);
    }
  }
);

// 导出 axios 实例
export default http;
